package threadSynchronization;

/**
 * @description: 使用多线程，模拟三个窗口同时售票
 * @author: Liuwanqing
 * @date: 2022-10-14 16:42
 */
public class  SellTicket {
    public static void main(String[] args) {
        SellTickets02 sellTickets02 = new SellTickets02();

//        SellTickets01 sellTickets01 = new SellTickets02();
//        SellTickets01 sellTickets02 = new SellTickets02();
//        SellTickets01 sellTickets03 = new SellTickets02();

//        sellTickets01.start();
//        sellTickets02.start();
//        sellTickets03.start();

        // 创建 3 个线程进行买票
        Thread thread1 = new Thread(sellTickets02);
        Thread thread2 = new Thread(sellTickets02);
        Thread thread3 = new Thread(sellTickets02);

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

// 使用 Thread 方式
class SellTickets01 extends Thread {
    private static int tikectNum = 100; // 多线程共享的 num

    @Override
    public synchronized void run() {
        while (true) {
            if (tikectNum <= 0) {
                System.out.println("票卖完了~~~");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出了一张票，还剩的票数为" + (--tikectNum) );
        }
    }
}
// 使用实现 Runnable 接口的方式
class SellTickets02 implements Runnable {
    private static int tikectNum = 100; // 多线程共享的 num

    @Override
    public void run() {
        while (true) {
            if (tikectNum <= 0) {
                System.out.println("票卖完了~~~");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出了一张票，还剩的票数为" + (--tikectNum) );
        }
    }
}
